package demo1;

import java.util.Arrays;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-05-22
 * Time: 18:08
 */

// Student 类实现 Comparable 接口
public class Student implements Comparable<Student> {
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';

    }

    @Override
    public int compareTo(Student o) {
//        return this.age - o.age;
        return o.name.compareTo(this.name);
    }

    //自己模拟实现，被调用接口里的，排序方法
//    public static void mySort(Comparable[] comparable) {  //这里用接口类型的数组接受，只要接口里有对应的方法，就可以通过实例化，这个接口类型的数组，来调用对应方法
//        for (int i = 0; i < comparable.length-1; i++) {
//            for (int j = 0; j < comparable.length-1-i; j++) {
//                /**
//                 * 注意：数组是引用类型（相当于地址），不可以这样比较(comparable[j] > comparable[j+1])
//                 */
//
//                if (comparable[j].compareTo(comparable[j+1]) > 0) {
//                    Comparable tmp = comparable[j];
//                    comparable[j] = comparable[j+1];
//                    comparable[j+1] = tmp;
//                }
//            }
//        }
//    }

    public static void main1(String[] args) {
        /*Student student1 =  new Student("wada", 2);
        Student student2 =  new Student("lili",4);
        Student student3 =  new Student("huahua",3);

        // sort 方法中会自动调用 compareTo 方法，传入student对象
        System.out.println(student1.compareTo(student2));//这里谁，调用了compareTo，谁就是compareTo方法中的this.*/

        /*Student[] student =  new Student[3];
        student[0] = new Student("wada", 4);
        student[1] = new Student("lili", 3);
        student[2] = new Student("huahua", 2);
        System.out.println("排序前" + Arrays.toString(student));


        Arrays.sort(student);
        System.out.println("排序后" + Arrays.toString(student));*/
    }


    /*@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }*/

    public static void main(String[] args) {
        NameComparator nameComparator = new NameComparator();

        Student[] student =  new Student[3];
        student[0] = new Student("wada", 8);
        student[1] = new Student("lili", 9);
        student[2] = new Student("huahua", 10);


        System.out.println("排序前" + Arrays.toString(student));


        Arrays.sort(student, nameComparator);//这里要，多传一个，构造器对象
        System.out.println("排序后" + Arrays.toString(student));



    }

}
